
import { computed,ref } from "vue"
function useFocus(data, callback) {
    //初始化表示没有任何一个元素被选中
    let selectIndex=ref(-1)
    //拿到点击的最后一项
    const lastSelectBlock=computed(()=>data.value.blocks[selectIndex.value])
    //计算所有失去焦点的元素和获得焦点的元素
    const focusData = computed(() => {
        let focus = []
        let unfocuesed = []
        data.value.blocks.forEach(block => (block.focus ? focus : unfocuesed).push(block))
        return {
            focus,
            unfocuesed
        }
    })
    //鼠标按下当前画布中的元素时，如果按住键盘shift,则把
    const blockMousedown = (e, block,index) => {
        e.stopPropagation()
        e.preventDefault();
        //在block上加一个属性focus获取焦点后将focus变为true
        if (e.shiftKey) {
            console.log( block.focus,'shiftKey');
            
            block.focus = !block.focus
        }
        else {
            if (!block.focus) {
                clearBlocksFocus()
                block.focus = true
            }
        }
        selectIndex.value=index
        callback && callback(e)

    }
    const clearBlocksFocus = () => {
        data.value.blocks.forEach(block => {
            block.focus = false
        })
    }
    const containerMousedown = () => {
        selectIndex.value=-1
        clearBlocksFocus()
     
    }

    return {
        containerMousedown,
        blockMousedown,
        focusData,
        lastSelectBlock
    }
}

export default useFocus